package com.foreknow.elm.service.impl;

import com.foreknow.elm.dao.CartDao;
import com.foreknow.elm.dao.impl.CartDaoImpl;
import com.foreknow.elm.po.Cart;
import com.foreknow.elm.service.CartService;
import com.foreknow.elm.util.DBUtil;
import sun.security.pkcs11.Secmod;

import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(String userId) {
        List<Cart> list = new ArrayList<>();
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            list = dao.listCart(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public int saveCart(String userId, Integer businessId, Integer foodId) {
        int i = 1 ;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            i = dao.saveCart(userId,businessId,foodId);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {
            DBUtil.close();
        }
        return i;
    }

    @Override
    public int updateCart(String userId, Integer businessId, Integer foodId, Integer quantity) {
        int i = 1 ;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            i = dao.updateCart(userId,businessId,foodId,quantity);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {
            DBUtil.close();
        }
        return i;
    }
    @Override
    public int removeCart(String userId, Integer businessId, Integer foodId) {
        int i = 1 ;
        CartDao dao = new CartDaoImpl();
        try {
            DBUtil.getConnection();
            DBUtil.beginTransaction();
            i = dao.removeCart(userId,businessId,foodId);
            DBUtil.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                DBUtil.rollbackTransaction();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }finally {
            DBUtil.close();
        }
        return i;
    }
}
